Parse.Cloud.define('deleteMenu', async (req, res) => {
  const user = req.user
  const { id } = req.params
  if (!user) {
    return res.error('请先登录')
  }
  if (!id) {
    return res.error('请选择需要删除的菜单')
  }
  const permission = { sessionToken: user.getSessionToken() }

  const menu = new Parse.Object('Menu')
  menu.id = id

  try {
    const findCurrent = new Parse.Query('Menu').equalTo('objectId', id).first(permission)
    const parentCount = new Parse.Query('Menu').equalTo('parent', menu).count(permission)
    const current = await findCurrent
    const isHasChild = await parentCount

    if (!current) {
      return res.error('没有该菜单')
    }
    if (isHasChild) {
      return res.error('还有子菜单，不能删除')
    }

    await current.destroy(permission)

    res.success('ok')
  } catch (err) {
    console.log(err)
    res.error(err.message)
  }
})

